﻿CREATE TABLE [dbo].[JurnaleSolduriInitiale] (
    [IDJurnal]        INT             NOT NULL,
    [Cont]            [dbo].[TipCont] NOT NULL,
    [CodUnitate]      SMALLINT        CONSTRAINT [DF_JurnaleSolduriInitiale_CodUnitate] DEFAULT ((0)) NOT NULL,
    [DebitInitial]    DECIMAL (18, 2) CONSTRAINT [DF_JurnaleSolduriInitiale_DebitInitial] DEFAULT ((0)) NOT NULL,
    [CreditInital]    DECIMAL (18, 2) NOT NULL,
    [DebitPrecedent]  DECIMAL (20, 2) CONSTRAINT [DF_JurnaleSolduriInitiale_DebitPrecedent] DEFAULT ((0)) NOT NULL,
    [CreditPrecedent] DECIMAL (20, 2) CONSTRAINT [DF_JurnaleSolduriInitiale_CreditPrecedent] DEFAULT ((0)) NOT NULL,
    CONSTRAINT [PK_JurnaleSolduriInitiale] PRIMARY KEY CLUSTERED ([IDJurnal] ASC, [Cont] ASC, [CodUnitate] ASC),
    CONSTRAINT [FK_JurnaleSolduriInitiale_Conturi] FOREIGN KEY ([Cont], [CodUnitate]) REFERENCES [dbo].[Conturi] ([Cont], [CodUnitate]),
    CONSTRAINT [FK_JurnaleSolduriInitiale_Jurnale] FOREIGN KEY ([IDJurnal]) REFERENCES [dbo].[Jurnale] ([IDJurnal]),
    CONSTRAINT [FK_JurnaleSolduriInitiale_Unitati] FOREIGN KEY ([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])
);


GO


CREATE TRIGGER [dbo].[UpdateParinteJurnaleSolduriInitiale] 
	ON [dbo].[JurnaleSolduriInitiale]
   AFTER  INSERT,DELETE,UPDATE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @Cont dbo.TipCont
	DECLARE @IDJurnal int
	DECLARE @CodUnitate smallint

    DECLARE update_cursor CURSOR FOR  SELECT DISTINCT Cont,IDJurnal,CodUnitate FROM (SELECT * FROM inserted UNION SELECT * FROM deleted) crt
 	OPEN update_cursor
 	FETCH NEXT FROM update_cursor INTO @Cont,@IDJurnal,@CodUnitate
 	WHILE (@@FETCH_STATUS <> -1)
 	BEGIN
 		IF (@@FETCH_STATUS <> -2)
   		BEGIN   
   			EXEC balcon_UpdateSolduriInitialeJurnale @CodUnitate,@Cont,@IDJurnal
   		END
    	FETCH NEXT FROM update_cursor INTO @Cont,@IDJurnal,@CodUnitate
 	END
 	CLOSE update_cursor
 	DEALLOCATE update_cursor

END